package com.itheima.controller;

import com.itheima.pojo.Result;
import jakarta.servlet.http.Cookie;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import jakarta.servlet.http.HttpSession;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;

@RestController
public class SessionController {

    @GetMapping("/c1")
    public Result cookie01(HttpServletResponse response) {
        response.addCookie(new Cookie("Login_name", "zhangsan"));
        response.addCookie(new Cookie("Login_role", "讲师"));
        return Result.success();
    }

    @GetMapping("/c2")
    public Result cookie02(HttpServletRequest request){
        Cookie[] cookies = request.getCookies();
        for (Cookie cookie : cookies) {
            if (cookie.getName().equals("Login_name")) {
                System.out.println(cookie.getValue());
            }
        }
        return Result.success();
    }

    @GetMapping("s1")
    public Result session01(HttpSession session){
        session.setAttribute("loginUser", "tom");
        return Result.success();
    }

    @GetMapping("s2")
    public Result session02(HttpServletRequest request){
        HttpSession session = request.getSession();
        System.out.println(session.hashCode());
        Object attribute = request.getAttribute("loginUser");
        System.out.println(attribute);
        return Result.success();
    }
}
